package pl.edu.agh.ros.node.util;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.jivesoftware.smack.packet.Message;
import org.ros.node.Node;

import pl.edu.agh.ros.node.prop.Props;

public final class RosServiceUtils<Q, A> {

	public Message serializeServiceRequest(Q request, Node node, String type) {
		ByteBuffer buffer = node.getMessageSerializationFactory().newServiceRequestSerializer(type).serialize(request);
		byte[] bytes = new byte[buffer.capacity()];
		buffer.get(bytes);
		org.jivesoftware.smack.packet.Message chatMessage = new org.jivesoftware.smack.packet.Message();
		chatMessage.setBody(Props.XMPP_MSG_BODY);
		chatMessage.setProperty(Props.XMPP_MSG_VALUE, bytes);
		chatMessage.setProperty(Props.XMPP_MSG_TYPE, type);
		return chatMessage;
	}

	@SuppressWarnings("unchecked")
	public Q deserializeServiceRequest(Message message, Node node, String type) {
		ByteBuffer buffer = ByteBuffer.wrap((byte[]) message.getProperty(Props.XMPP_MSG_VALUE));
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		Q msg = (Q) node.getMessageSerializationFactory().newServiceRequestDeserializer(type).deserialize(buffer);
		return msg;
	}

	public Message serializeServiceResponse(A response, Node node, String type) {
		ByteBuffer buffer = node.getMessageSerializationFactory().newServiceResponseSerializer(type)
				.serialize(response);
		byte[] bytes = new byte[buffer.capacity()];
		buffer.get(bytes);
		org.jivesoftware.smack.packet.Message chatMessage = new org.jivesoftware.smack.packet.Message();
		chatMessage.setBody(Props.XMPP_MSG_BODY);
		chatMessage.setProperty(Props.XMPP_MSG_VALUE, bytes);
		chatMessage.setProperty(Props.XMPP_MSG_TYPE, type);
		return chatMessage;
	}

	@SuppressWarnings("unchecked")
	public A deserializeServiceResponse(Message message, Node node, String type) {
		ByteBuffer buffer = ByteBuffer.wrap((byte[]) message.getProperty(Props.XMPP_MSG_VALUE));
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		A msg = (A) node.getMessageSerializationFactory().newServiceResponseDeserializer(type).deserialize(buffer);
		return msg;
	}

}
